package com.wangwenjun.concurrency.chapter14.atomicinteger;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.IntUnaryOperator;

public class UseAtomicInteger {
    private static int a = 0;

    public static void main(String[] args) throws InterruptedException {
        AtomicInteger integer = new AtomicInteger(2002);
        CountDownLatch countDownLatch = new CountDownLatch(100000);

        for (int i = 1; i <= 100000; i++) {
            new Thread(() -> {
                addAndGet(integer, key -> key + 2);
                countDownLatch.countDown();
            }).start();
        }
        countDownLatch.await();
        System.out.println(integer);
    }

    private static void add(AtomicInteger ai){
        while (true){
            int prev = ai.get();
            int now = prev + 1;
            if(ai.compareAndSet(prev, now)){
                break;
            }
        }
    }

    private static void addAndGet(AtomicInteger ai, IntUnaryOperator operator){
        while (true){
            if(ai.compareAndSet(ai.get(), operator.applyAsInt(ai.get()))){
                return;
            }
        }
    }




}
